import asyncio
import websockets
import time


# 如果” _ _ new _ _ “没有返回cls（即当前类）的实例，那么当前类的” _ _ init _ _”方法是不会被调用的。
class MyServer(object):
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.websocket_gp = None
        print("init %s" % self.__class__)

    # def __new__(cls, ip, port):
    #     print("new %s" % cls)
    #     print(ip)
    #     print(port)
    #     return object.__new__(cls)

    # 定义WebSocket处理逻辑
    async def websocket_handler(self, websocket, path):
        # 接收客户端消息
        self.websocket_gp = websocket
        async for message in websocket:
            print(message)
            # 发送响应给客户端
            await websocket.send('服务器收到了消息，回复OK')
        # 服务器分发一个消息到客户端

    # 处理消息的函数
    def process_message(self, message):
        # 处理逻辑...
        return 'response'

    def send(self, message):
        if self.websocket_gp:
            asyncio.run(self.websocket_gp.send(message))

    # 定义一个专门创建事件循环loop的函数，在另一个线程中启动它
    def start_loop(self, loop):
        asyncio.set_event_loop(loop)
        loop.run_forever()

    async def start_server(self):
        websockets.serve(self.websocket_handler, self.ip, self.port)

    def start(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        # 启动WebSocket服务器
        start_server = websockets.serve(self.websocket_handler, "localhost", 8888)

        # 运行事件循环
        asyncio.get_event_loop().run_until_complete(start_server)
        asyncio.get_event_loop().run_forever()


if __name__ == '__main__':
    server = MyServer('localhost', 8888)
    server.start()
